package com.example.androidservicetutorial;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.androidservicetutorial.service.BroadcastReceiverService;

public class ProgressBroadcastReceiverActivity extends AppCompatActivity {
    private ProgressBar mProgressBar;
    private Button btnDownload;
    private MyProgressBroadcastReceiver receiver;
    private Intent intent;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_progress_service);
        mProgressBar = findViewById(R.id.progressBar);
        btnDownload = findViewById(R.id.btnDownload);

        receiver = new MyProgressBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.MY_RECEIVER");
        registerReceiver(receiver,intentFilter);

        btnDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent = new Intent(ProgressBroadcastReceiverActivity.this, BroadcastReceiverService.class);
                startService(intent);
            }
        });
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(receiver);
        stopService(intent);
        super.onDestroy();
    }

    class MyProgressBroadcastReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            int progress = intent.getIntExtra("progress",0);
            Log.e("progress","receiver progress:" + progress);
            mProgressBar.setProgress(progress);
        }
    }
}
